package cn.edu.zafu.bigdata.Wym;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Wym_UDPClockServer {
    public static void main(String[] args) throws Exception {
        // 创建一个 DatagramSocket 实例，监听端口 12345
        DatagramSocket socket = new DatagramSocket(12345);

        // 定义一个用于发送时间的字节数组
        byte[] buffer = new byte[1024];

        while (true) {
            // 接收客户端发送的数据包
            DatagramPacket request = new DatagramPacket(buffer, buffer.length);
            socket.receive(request);

            // 获取当前服务器时间
            String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

            // 将时间字符串转换为字节数组
            byte[] responseBuffer = currentTime.getBytes();

            // 获取客户端地址和端口
            InetAddress clientAddress = request.getAddress();
            int clientPort = request.getPort();

            // 创建响应数据包并发送
            DatagramPacket response = new DatagramPacket(responseBuffer, responseBuffer.length, clientAddress, clientPort);
            socket.send(response);
        }
    }
}
